package com.export.document.controller;

import com.export.document.service.ExportDocService;
import lombok.extern.log4j.Log4j2;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

@RestController
@RequestMapping("/export")
@Log4j2
public class ExportDocController {
    @Autowired
    private ExportDocService exportService;

    /**
     * 导出文档据库表
     *
     * @param shcemaName
     * @return
     */
    @GetMapping("/exportDoc")
    public String exportDoc(String shcemaName, String tableName, String fileName, boolean isTest, HttpServletResponse response) throws Exception {
        log.info("导出文档据库字典shcemaName:{}", shcemaName);

        Workbook wb = exportService.exportDoc(shcemaName, tableName);
        if (!isTest) {
            exportService.save(fileName);
            OutputStream output = response.getOutputStream();
            response.reset();
            //文件名如为中文,需改变编码集
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(), "iso-8859-1") + ".xlsx");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            wb.write(output);
            output.close();
            output.flush();
        }
        return "";
    }
}
